package com.thread.example.third;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String cardId;

    private double money;

    private Lock lock = new ReentrantLock();

    public Account() {
    }

    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
    /**
     * 使用synchronized解决线程安全问题
     * */
    public void drawMoney(double money){
        String name = Thread.currentThread().getName();
            for(int i=0;i<51;i++){

                if (this.money >= money) {
                    this.money = this.money - money;
                    System.out.println(name + "来取钱，还剩余:" + this.money);
                } else {
                    System.out.println(name + "钱取完了");
                }

        }
    }
    /**
     * lock锁解决线程问题
     *
     * */
    public void drawMoneyLock(double money){
        String name = Thread.currentThread().getName();
        try {
            lock.lock();
            if(this.money>=money){
                System.out.println(name+"来去钱"+money+"成功");
                this.money = this.money-money;
                System.out.println(name+"来取钱，还剩余:"+this.money);
            }else{
                System.out.println(name+"钱取完了");
            }
        } catch (Exception e) {
            System.out.println("错误");
        } finally {
            lock.unlock();
        }

    }
}
